<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-01-15
 * @Time: 15:18
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： Special.php
 */
namespace app\api\controller;

use app\api\model\special\SpecialArticle;
use app\api\model\special\SpecialArticleMessage;
use app\api\model\special\SpecialColumn;
use app\api\model\special\UserSubscribeSpecial;
use app\api\model\Teacher;
use app\common\controller\Base;
use app\common\model\ApiResponse;
use app\common\model\teacher\TeacherEssay;
use app\common\model\user\EssayLiked;
use think\Request;
use think\Validate;

class Special extends Base {
    protected $column, $article, $message;

    public function __construct()
    {
        parent::__construct();

        $this->column = new SpecialColumn();
        $this->article = new SpecialArticle();
        $this->message = new SpecialArticleMessage();
    }

    /**
     * column
     * 专栏栏目列表数据接口
     * @api http://xxx/api/special/column
     *      POST
     *          page 选填 当前页数
     *          limit 选填 每页加载数据条数
     *
     * @author zhengkai
     * @date 2018-01-15
     * @version 1.3
     *
     * @return \think\response\Json
     */
    public function column()
    {
        $uid = checkUserToken(false);

        $form = input('post.');

        // 表单验证
        $validate = new Validate([
            ['page', '^\\d+$', 'page参数类型不正确'],
            ['limit', '^\\d+$', 'limit参数类型不正确']
        ]);
        if(!$validate->check($form)) return json(array('code'=>1010, 'msg'=>$validate->getError(), 'data'=>null));

        if (!isset($form['page'])) $form['page'] = 1;
        if (!isset($form['limit'])) $form['limit'] = 10;

        $result = $this->column->getColumn($uid, $form['page'], $form['limit']);

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * detail
     * 专栏栏目详情数据接口
     * @api http://xxx/api/special/detail
     *      POST
     *          column_id 必填 栏目id
     *
     * @author zhengkai
     * @date 2018-01-16
     * @version 1.3
     *
     * @return \think\response\Json
     */
    public function detail()
    {
        $uid = checkUserToken(false);

        $form = input('post.');

        // 表单验证
        $validate = new Validate([
            ['column_id', 'require|^\\d+$', '栏目ID不能为空|column_id参数类型不正确']
        ]);
        if(!$validate->check($form)) return json(array('code'=>1010, 'msg'=>$validate->getError(), 'data'=>null));

        $result = $this->column->getSingleColumn($uid, $form['column_id']);
        $result['first_column_new_article_id']=$result['column_new_article'][0]['id']??0;

        if (empty($result)) {
            return ApiResponse::error(ApiResponse::ERR_RESOURCE_NON,'专栏不存在');
        }

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * article_list
     * 专栏栏目文章列表数据接口
     * @api http://xxx/api/special/article/list
     *      POST
     *          column_id 必填 栏目id
     *          page      选填 当前页数
     *          limit     选填 每页加载数据条数
     *
     * @author zhengkai
     * @date 2018-01-16
     * @version 1.3
     *
     * @return \think\response\Json
     */
    public function article_list()
    {
        $form = input('post.');

        // 表单验证
        $validate = new Validate([
            ['column_id', 'require|^\\d+$', '栏目ID不能为空|column_id参数类型不正确'],
            ['page', '^\\d+$', 'page参数类型不正确'],
            ['limit', '^\\d+$', 'limit参数类型不正确']
        ]);
        if(!$validate->check($form)) return json(array('code'=>1010, 'msg'=>$validate->getError(), 'data'=>null));

        if (!isset($form['page'])) $form['page'] = 1;
        if (!isset($form['limit'])) $form['limit'] = 10;

        $column = SpecialColumn::getBaseColumn($form['column_id'], 'detail');

        if ($column) {
            $column_subscribe_total = countDataNum(UserSubscribeSpecial::totalSubscribe($form['column_id']), $column['feed'], true);

            $result = [
                'column_info' => $column,
                // 专栏自定义订阅数小于实际订阅数时显示实际订阅数
                'column_subscribe_total' => $column_subscribe_total,
                'column_article_total' => SpecialArticle::totalArticle($form['column_id']),
                'column_article_list' => $this->article->getArticle($form['column_id'], $form['page'], $form['limit']),
                'column_share_url' => SpecialColumn::shareUrl($column['column_id']),
            ];
            $result['column_article_page_total'] = ceil($result['column_article_total'] / $form['limit']);
            unset($result['column_info']['column_teacher']);
            unset($result['column_info']['column_updatetime']);
            unset($result['column_info']['feed']);
        } else {
            $result = (object)[];
        }
        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * article_detail
     * 专栏栏目文章详情数据接口
     * @api http://xxx/api/special/article/detail
     *      POST
     *          article_id 必填 文章id
     *
     * @author zhengkai
     * @date 2018-01-16
     * @version 1.3
     *
     * @return mixed
     */
    public function article_detail()
    {
        $uid = checkUserToken(false);

        $form = input('post.');

        // 表单验证
        $validate = new Validate([
            ['article_id', 'require|^\\d+$', '文章ID不能为空|article_id参数类型不正确'],
        ]);
        if(!$validate->check($form)) return json(array('code'=>1010, 'msg'=>$validate->getError(), 'data'=>null));

        $article = $this->article->getSingleArticle($form['article_id'], $this->isAPP());
        if ($article['special_column_id'] == 0) return ApiResponse::error(ApiResponse::ERR_RESOURCE_NON,'文章不存在');

        if ($article) {
            $column = SpecialColumn::getBaseColumn($article['special_column_id'], 'list', $uid);
            $teacher = Teacher::getBaseTeacher($column['column_teacher']);
            $message = $this->message->getMessage($form['article_id'], 1 ,10);

            $article['teacher_id'] = $teacher['teacher_id'];
            $article['teacher_name'] = $teacher['teacher_name'];
            $article['teacher_avatar'] = $teacher['teacher_avatar'];
            $article['teacher_article_total'] = $teacher['teacher_article_total'];
            $article['teacher_followed_total'] = $teacher['teacher_followed_total'];
            $article['teacher_info'] = $teacher['teacher_info'];
            $article['like_status'] = SpecialArticle::checkLiked($uid, $article['id']) ? 1 : 0;
            $article['like_num'] = EssayLiked::takeCount($article['id']);
            $column['column_subscribe_status'] = UserSubscribeSpecial::isBuy($uid, $article['special_column_id']);

            // 专栏自定义订阅数小于实际订阅数时显示实际订阅数
            $column['column_subscribe_total'] = countDataNum(UserSubscribeSpecial::totalSubscribe($article['special_column_id']), $column['feed'], true);

            if(!$column->free && 1 != $column['column_subscribe_status']){
                $article->content =isset($article->content) ? mb_substr(stripHtml($article->content),0,400) : '';
                if (isset($article->attachment)) {
                    $article->attachment->audio=new \stdClass();
                    $article->attachment->video=new \stdClass();
                }
            }

            $token = Request::instance()->token;
            $article['article_url'] = SpecialArticle::articleUrl($article['id'],$uid,$token);

            $result = [
                'article' => $article,
                'column' => $column,
                'message' => $message,
                'share_url' => SpecialArticle::shareUrl($article['special_column_id'], $article),
                'related' => SpecialArticle::getRelatedArticle($article['special_column_id'], $form['article_id'])
            ];
        } else {
            return ApiResponse::error(ApiResponse::ERR_RESOURCE_NON,'文章不存在');
        }

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * article_message_commit
     * 专栏文章留言提交接口
     * @api http://xxx/api/special/article/message/commit
     *      POST
     *          article_id 必填 文章id
     *          message_content 必填 留言内容
     *
     * @author zhengkai
     * @date 2018-01-16
     * @version 1.3
     *
     * @return \think\response\Json
     */
    public function article_message_commit()
    {
        $uid = checkUserToken(true);

        $form = input('post.');

        // 表单验证
        $validate = new Validate([
            ['article_id', 'require|^\\d+$', '文章ID不能为空|article_id参数类型不正确'],
            ['message_content', 'require', '留言内容不能为空']
        ]);
        if(!$validate->check($form)) return json(array('code'=>1010, 'msg'=>$validate->getError(), 'data'=>null));

        $data = [
            'message_article' => $form['article_id'],
            'message_user' => $uid,
            'message_content' => $form['message_content']
        ];

        $result = $this->message->saveMessage($data);

        if ($result) {
            return json(array('code'=>200, 'msg'=>'留言成功！', 'data'=>null));
        } else {
            return json(array('code'=>1012, 'msg'=>'留言失败！', 'data'=>null));
        }
    }

    /**
     * article_message_list
     * 专栏文章留言列表数据接口
     * @api http://xxx/api/special/article/message/list
     *      POST
     *         article_id 必填 文章id
     *
     * @author zhengkai
     * @date 2018-01-16
     * @version 1.3
     *
     * @return \think\response\Json
     */
    public function article_message_list()
    {
        $form = input('post.');

        // 表单验证
        $validate = new Validate([
            ['article_id', 'require|^\\d+$', '文章ID不能为空|article_id参数类型不正确'],
            ['page', '^\\d+$', 'page参数类型不正确'],
            ['limit', '^\\d+$', 'limit参数类型不正确']
        ]);
        if(!$validate->check($form)) return json(array('code'=>1010, 'msg'=>$validate->getError(), 'data'=>null));

        if (!isset($form['page'])) $form['page'] = 1;
        if (!isset($form['limit'])) $form['limit'] = 10;

        $result = $this->message->getMessage($form['article_id'], $form['page'] ,$form['limit']);

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * pc_index
     * pc首页专栏
     *
     * @author zhengkai
     * @date 2018-04-23
     *
     * @return array|false|string|static[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function pc_index()
    {

        $form = input('post.');
        $validate = new Validate([
            ['limit', 'integer', 'limit参数类型不正确']
        ]);
        if(!$validate->check($form)) return json(array('code'=>1010, 'msg'=>$validate->getError(), 'data'=>null));

        if (!isset($form['limit'])) $form['limit'] = 3;

        $result = SpecialColumn::getRecommendColumn($form['limit']);

        return $result;
    }
}